﻿using Sys.Common;
using Sys.Core.Gen;
using Sys.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Sys.Api.Gen
{
    public class NewApi : BaseApi
    {
        public string Grid(int rows, int page, string search, string dictionaryid, string sort, string order)
        {
            var entities = NewBll.I.Entities;

            if (!string.IsNullOrEmpty(search))
            {
                entities = entities.Where(m => m.Name.Contains(search));
            }

            if (!string.IsNullOrEmpty(dictionaryid) && !dictionaryid.Equals("Null"))
            {
                entities = entities.Where(m => m.DictionaryID.Equals(dictionaryid));
            }

            var list = NewBll.I.EntitiesPage(entities, rows, page, sort, order);

            var select = list.Select(m => new
            {
                ID = m.ID,
                Name = m.Name,
                Top = m.Top,
                InsertTime = m.InsertTime,
                UpdateTime = m.UpdateTime
            });

            return GetGrid(entities.Count(), select.ToList());
        }

        public string Save(GenNew model)
        {
            JsonMsg result = new JsonMsg();

            if (string.IsNullOrEmpty(model.ID))
            {
                result.Message = "添加成功!";

                model.ID = StringHelper.GetGuid();

                model.InsertTime = DateTime.Now;
                model.UpdateTime = DateTime.Now;

                result.Success = NewBll.I.Insert(model) > 0;
            }
            else
            {
                result.Message = "修改成功!";

                model.UpdateTime = DateTime.Now;

                result.Success = NewBll.I.Update(model) > 0;
            }

            if (!result.Success) { result.Message = "操作失败!"; }

            return JsonHelper.ToJson(result);
        }

        public string Top(string id)
        {
            JsonMsg result = new JsonMsg();

            GenNew model = NewBll.I.GetByKey(id);

            if (model != null)
            {
                model.Top = !model.Top;

                result.Success = NewBll.I.Update(model) > 0;

                if (result.Success)
                {
                    if (model.Top)
                    {
                        result.Message = "顶置成功!";
                    }
                    else
                    {
                        result.Message = "撤销成功!";
                    }
                }
            }

            return JsonHelper.ToJson(result);
        }

        public string Delete(string id)
        {
            JsonMsg result = new JsonMsg();

            result.Success = NewBll.I.Delete(id) > 0;

            if (result.Success) { result.Message = "删除成功!"; }

            return JsonHelper.ToJson(result);
        }
    }
}